package com.yaoweigroup.community.util;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.config.Constant;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.UserInfo;

public class LoginUtil {

	public static final int LOGIN_SUCCESS = 0x23456;;
	public static final int LOGIN_FAIL = LOGIN_SUCCESS + 1;

	public static void isLoginSuccess(Context context, final Handler handler,
			final ObjectMapper mapper) {

		final SharePreferenceUtil util = new SharePreferenceUtil(context,
				Constant.prf);
		UserInfo user = (UserInfo) util.loadObject("user");
		if (user == null) {
			handler.sendEmptyMessage(LOGIN_FAIL);
			return;
		}
		HttpUtils http = UtilHttp.getHttpUtils(context);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("UserName", user.getUsername());
		jsonUtil.add("PassWord", user.getUserpass());
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.login, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							String message = obj.getString("message");
							if (state == 200) {
								UserInfo user = mapper.readValue(data,
										new TypeReference<UserInfo>() {
										});
								util.saveObject(user, "user");
								handler.sendEmptyMessage(LOGIN_SUCCESS);

							} else {
								Message msg = handler.obtainMessage();
								msg.what = LOGIN_FAIL;
								msg.obj = message;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(LOGIN_FAIL);
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(LOGIN_FAIL);
					}

				});
	}
}
